package me.qi.kancha.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xhyt.common.resource.support.TokenPrincipal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author sun
 * @date 2022/1/3 16:14
 * @modified By：
 */
@Component
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdBy", String.class, getName());
        this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "modifiedBy", String.class, getName());
        this.strictInsertFill(metaObject, "modifiedTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        this.strictInsertFill(metaObject, "version", Long.class, 1L);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "modifiedBy", String.class, getName());
        this.strictUpdateFill(metaObject, "modifiedTime", LocalDateTime.class, LocalDateTime.now());
    }

    private String getName() {
        String name = "unknown";
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx != null && ctx.getAuthentication() != null) {
            if (ctx.getAuthentication() instanceof OAuth2Authentication ) {
                OAuth2Authentication authentication = (OAuth2Authentication) ctx.getAuthentication();
                if (authentication.getUserAuthentication() == null) {
                    //客户端模式 返回clientId
                    name = authentication.getOAuth2Request().getClientId();
                } else {
                    TokenPrincipal principal = (TokenPrincipal) authentication.getUserAuthentication().getPrincipal();
                    name = (String) principal.getPrincipal().get("entityId");
                }
            } else {
                name = ctx.getAuthentication().getName();
            }
        }
        return name;
    }
}
